{% extends "base.html" %}

{% block title %}我的消息{% endblock %}

{% block content %}
<style>
    .message-card {
        background: white;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 20px;
        padding: 20px;
        transition: transform 0.2s;
        cursor: pointer;
    }
    
    .message-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    
    .message-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
    }
    
    .item-title {
        font-weight: bold;
        color: #333;
        font-size: 18px;
    }
    
    .message-time {
        color: #666;
        font-size: 14px;
    }
    
    .last-message {
        color: #666;
        margin-bottom: 10px;
    }
    
    .message-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .contact-name {
        color: #007bff;
        font-weight: 500;
    }
    
    .unread-badge {
        background: #dc3545;
        color: white;
        border-radius: 50%;
        padding: 2px 6px;
        font-size: 12px;
        font-weight: bold;
    }
    
    .new-badge {
        background: #dc3545;
        color: white;
        border-radius: 3px;
        padding: 2px 8px;
        font-size: 12px;
        font-weight: bold;
        text-transform: uppercase;
    }
    
    .no-messages {
        text-align: center;
        padding: 50px;
        color: #666;
    }
    
    .no-messages i {
        font-size: 48px;
        margin-bottom: 20px;
        color: #ddd;
    }
</style>

<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <h2 class="mb-4">
                <i class="fas fa-envelope"></i> 我的消息
            </h2>
            
            {% if conversations %}
                {% for conv in conversations %}
                <div class="message-card" onclick="openChat('{{ conv.item_id }}', '{{ conv.contact_id }}', '{{ conv.item_name }}', '{{ conv.contact_name }}', '{{ conv.item_type }}')">
                    <div class="message-header">
                        <div class="item-title">{{ conv.item_name }}</div>
                        <div class="message-time">{{ conv.last_time.strftime('%m-%d %H:%M') }}</div>
                    </div>
                    <div class="last-message">{{ conv.last_message }}</div>
                    <div class="message-info">
                        <div class="contact-name">与 {{ conv.contact_name }} 的对话</div>
                        {% if conv.unread_count > 0 %}
                        <span class="new-badge">NEW</span>
                        {% endif %}
                    </div>
                </div>
                {% endfor %}
            {% else %}
                <div class="no-messages">
                    <i class="fas fa-comments"></i>
                    <h4>暂无消息</h4>
                    <p>您还没有任何失物招领相关的对话</p>
                </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- 聊天模态框 -->
<div class="modal fade" id="chatModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="chatModalTitle">对话</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="chatMessages" class="chat-messages mb-3"></div>
                <div class="input-group">
                    <input type="text" id="messageInput" class="form-control" placeholder="输入消息...">
                    <button class="btn btn-primary" onclick="sendMessage()">发送</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let currentItemId = null;
let currentReceiverId = null;
let currentItemType = 'found';

function openChat(itemId, contactId, itemName, contactName, itemType = 'found') {
    currentItemId = itemId;
    currentReceiverId = contactId;
    currentItemType = itemType;
    
    document.getElementById('chatModalTitle').textContent = `${itemName} - 与${contactName}的对话`;
    
    // 移除NEW标记
    const messageCard = event.currentTarget;
    const newBadge = messageCard.querySelector('.new-badge');
    if (newBadge) {
        newBadge.remove();
    }
    
    // 加载消息历史
    loadMessages(itemId, itemType);
    
    // 显示模态框
    new bootstrap.Modal(document.getElementById('chatModal')).show();
}

function loadMessages(itemId, itemType = 'found') {
    fetch(`/get_messages/${itemId}/${itemType}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayMessages(data.messages);
            } else {
                alert('加载消息失败：' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('加载消息时发生错误');
        });
}

function displayMessages(messages) {
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.innerHTML = '';
    
    messages.forEach(message => {
        const messageDiv = document.createElement('div');
        const isMyMessage = message.sender_id == '{{ session.user_id }}';
        
        messageDiv.className = `message ${isMyMessage ? 'my-message' : 'other-message'}`;
        messageDiv.innerHTML = `
            <div class="message-content">${message.message}</div>
            <div class="message-time">${new Date(message.sent_time).toLocaleString()}</div>
        `;
        
        chatMessages.appendChild(messageDiv);
    });
    
    // 滚动到底部
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    
    if (!message) {
        alert('请输入消息内容');
        return;
    }
    
    fetch('/send_message', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            item_id: currentItemId,
            receiver_id: currentReceiverId,
            message: message,
            item_type: currentItemType
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            messageInput.value = '';
            loadMessages(currentItemId, currentItemType);
        } else {
            alert('发送失败：' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发送消息时发生错误');
    });
}

// 回车发送消息
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('messageInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
});
</script>

<style>
.chat-messages {
    height: 400px;
    overflow-y: auto;
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 10px;
    background-color: #f8f9fa;
}

.message {
    margin-bottom: 15px;
    display: flex;
    flex-direction: column;
}

.my-message {
    align-items: flex-end;
}

.other-message {
    align-items: flex-start;
}

.message-content {
    background: #007bff;
    color: white;
    padding: 8px 12px;
    border-radius: 15px;
    max-width: 70%;
    word-wrap: break-word;
}

.other-message .message-content {
    background: #e9ecef;
    color: #333;
}

.message-time {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
}
</style>
{% endblock %}